package com.meeting.controller.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.meeting.dto.LoginDTO;
import com.meeting.dto.RegisterDTO;
import com.meeting.dto.UpdatePasswordDTO;
import com.meeting.mapper.CustomerMapper;
import com.meeting.vo.Result;
import com.meeting.entity.Customer;
import com.meeting.service.CustomerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/customer")
@Tag(name = "客户接口")
@Slf4j
public class CustomerLoginController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerMapper customerMapper;

    @PostMapping("/login")
    @Operation(summary = "客户登录")
    public Result login(@RequestBody LoginDTO loginDTO) {
        log.info("客户登录请求：{}", loginDTO);
        return customerService.login(loginDTO);
    }

    @PostMapping("/register")
    @Operation(summary = "客户注册")
    public Result register(@RequestBody RegisterDTO registerDTO) {
      log.info("用户注册请求：{}",registerDTO);
      return customerService.register(registerDTO);
    }

    // 新增：客户登出接口
    @PostMapping("/logout")
    @Operation(summary = "客户登出")
    public Result logout() {
        log.info("客户登出请求");
        return customerService.logout();
    }



    // 修改：根据用户名获取客户信息
    @GetMapping("/selectByUsername/{username}")
    @Operation(summary = "根据用户名获取客户信息")
    public Result getCustomerByUsername(@PathVariable String username) {
        log.info("获取客户信息，用户名：{}", username);
        // 使用LambdaQueryWrapper通过用户名查询
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getUsername, username);

        Customer customer = customerMapper.selectOne(queryWrapper);
        if (customer == null) {
            return Result.error("客户不存在");
        }
        // 清除敏感信息
        customer.setPassword(null);
        return Result.success(customer);
    }




    // 新增：更新客户信息
    @PutMapping("/update")
    @Operation(summary = "更新客户信息")
    public Result updateCustomer(@RequestBody Customer customer) {
        log.info("更新客户信息：{}", customer);
        int result = customerMapper.updateById(customer);
        if (result > 0) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    // 新增：修改密码
    /**
     * 基于用户名的密码修改方法
     */
    @PostMapping("/updatePassword")
    @Operation(summary = "修改客户密码")
    public Result updatePassword(@RequestBody UpdatePasswordDTO updatePasswordDTO) {
        log.info("密码修改请求 - 用户名：{}", updatePasswordDTO.getUsername());

        // 参数基础验证
        if (!validatePasswordParams(updatePasswordDTO)) {
            return Result.error("密码参数不合法");
        }

        try {
            // 通过用户名获取客户信息
            Customer customer = customerMapper.selectOne(
                    new LambdaQueryWrapper<Customer>()
                            .eq(Customer::getUsername, updatePasswordDTO.getUsername())
            );

            // 验证客户是否存在
            if (customer == null) {
                return Result.error("客户不存在");
            }

            // 验证原密码（建议实际使用时加密比对）
            if (!customer.getPassword().equals(updatePasswordDTO.getOldPassword())) {
                return Result.error("原密码验证失败");
            }

            // 更新密码
            customer.setPassword(updatePasswordDTO.getNewPassword());
            int result = customerMapper.updateById(customer);

            return result > 0 ? Result.success("密码更新成功") : Result.error("密码更新失败");

        } catch (Exception e) {
            log.error("密码修改异常 - 用户名：{}，错误：{}",
                    updatePasswordDTO.getUsername(), e.getMessage());
            return Result.error("系统繁忙，请稍后重试");
        }
    }

    /**
     * 密码参数验证方法
     */
    private boolean validatePasswordParams(UpdatePasswordDTO dto) {
        return dto.getUsername() != null && !dto.getUsername().isEmpty()
                && dto.getOldPassword() != null && !dto.getOldPassword().isEmpty()
                && dto.getNewPassword() != null && !dto.getNewPassword().isEmpty()
                && !dto.getNewPassword().equals(dto.getOldPassword());
    }
//    @PostMapping("/updatePassword")
//    @Operation(summary = "修改客户密码")
//    public Result updatePassword(@RequestBody Customer customer, @RequestParam String newPassword) {
//        log.info("修改密码，客户ID：{}", customer.getId());
//
//        // 验证原密码
//        Customer existCustomer = customerMapper.getByUsername(customer.getUsername());
//        if (existCustomer == null || !existCustomer.getPassword().equals(customer.getPassword())) {
//            return Result.error("原密码错误");
//        }
//
//        // 更新新密码
//        existCustomer.setPassword(newPassword);
//        int result = customerMapper.updateById(existCustomer);
//        if (result > 0) {
//            return Result.success("密码修改成功");
//        }
//        return Result.error("密码修改失败");
//    }



}